import {
	ref
} from "vue";
import {
	post
} from "/common/api.js"
import {
	onShow,
	onPullDownRefresh,
	onReachBottom
} from "@dcloudio/uni-app";

export function usePage(functionMethod, searchObject) {
	//集合
	let pageData = ref({})
	//加载的状态
	const status = ref("more")
	//总页数
	const totalPage = ref(0)
	//总条数
	const total = ref(0)


	const initData = async () => {
		searchObject.value.no = 1
		await getData();
		uni.stopPullDownRefresh();
	};
	onPullDownRefresh(async () => {
		await initData();
	})

	const checkMore = (res) => {
		totalPage.value = res.totalPage;
		total.value = res.total;
		if (searchObject.value.no < res.totalPage) {
			status.value = "loading";
		} else {
			status.value = "noMore";
		}

	}

	const getData = async () => {
		let res = await post(functionMethod, searchObject.value);
		if (res.code !== 200) {
			uni.showModal({
				content: res.msg,
				showCancel: false
			})
			return;
		}
		checkMore(res)
		pageData.value = res.data;

	};

	const loadMore = async () => {

		searchObject.value.no = searchObject.value.no + 1;
		if(searchObject.value.no>totalPage.value){
			status.value = "noMore";
			return;
		}
		let res = await post(functionMethod, searchObject.value);
		if (res.code !== 200) {
			return;
		}
		checkMore(res)
		if (res.data) {
			pageData.value = pageData.value.concat(res.data);
		}

	}

	onReachBottom(async () => {
		await loadMore();
	});

	onShow(async () => {
		await getData()
	})
	return {
		pageData,
		status,
		totalPage,
		initData,
		total,
		loadMore
	}
}
